package fr.upmc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import fr.upmc.bean.Contact;
import fr.upmc.dao.ContactDAO;
import fr.upmc.utils.HibernateUtils;
import fr.upmc.utils.SessionTracker;

public class UpdateContact extends HttpServlet {

	private static final long serialVersionUID = -3453344416059884923L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		//if user not connected, get him the hell out of here
		if(!SessionTracker.isUserConnected(request))
		{
			SessionTracker.redirectToHome(response);
		}
		
		Session session = HibernateUtils.getSessionFactory().openSession();
		ContactDAO dao = new ContactDAO(session);
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		
		long id = Long.parseLong(request.getParameter("contactId"));
		String firstName = request.getParameter("firstname");
		String lastName = request.getParameter("lastname");
		String email = request.getParameter("email");

		String street = request.getParameter("street");
		String city = request.getParameter("city");
		String zip = request.getParameter("zip");
		String country = request.getParameter("country");
		
		
		
		Contact contact = dao.read(id);
		if(contact == null){
			out.print("error");
			return;
		}

		contact.setFirstName(firstName);
		contact.setLastName(lastName);
		contact.setEmail(email);
		contact.setContactId(id);

		contact.getAddress().setStreet(street);
		contact.getAddress().setCountry(country);
		contact.getAddress().setZip(zip);
		contact.getAddress().setCity(city);
		

		//out.println("<html><body>");

		if(dao.update(contact)){
			out.print("success");
		}
		else{
			out.print("error");
		}

		//out.println("</body></html>");
		out.close();
		session.close();

		return;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		doGet(request,response);

		return;
	}
}
